import { createElement, useContext, useRef } from "react";
import {handleEvent} from "./eventHandler"
import { LowCodePageContext } from '@/pages/lowCodeEditorPlus/contextProvider/LowCodePageProvider';
import { ComponentConfig, useComponentConfigStore } from "@/stores/low-editor-comps-conf";
import { Component, useComponentsStore } from "@/stores/edit-pages-store";

export type EventExtraType = {
  ancestorDataProperties: Record<string, any>
}
export function renderProdComponents(
  schemas: Component[],
  extra?: EventExtraType
){
  const { schema } = useComponentsStore();
  const { flatComponentConfig } = useComponentConfigStore();
  const componentConfig = flatComponentConfig();
  const { componentRefs } = useContext(LowCodePageContext)

  function renderComponents(
    schemas: Component[],
    extra?:{
      ancestorDataProperties:Record<string, any>
    }
  ): React.ReactNode {
    return schemas.map(component => {
      const config = componentConfig?.[component.name];
      if (!config?.prod) null;
      const defaultProps = typeof config.defaultProps === 'function' ? config.defaultProps() : config.defaultProps;
      return createElement(
        config?.prod,
        {
          key: component.id,
          id: component.id,
          name: component.name,
          styles: component.styles,
          ref:
            config.prod?.$$typeof === Symbol.for("react.forward_ref")
              ? (ref: Record<string, any>) => {
                if(componentRefs.current){componentRefs.current[component.id] = ref}
                }
              : undefined,
          
          ...component?.innerName&&{innerName: component.innerName},
          ...defaultProps,
          ...component.props,
          ...handleEvent(component, componentConfig, componentRefs, schema, extra),
          header: renderComponents(component?.header || []),
          aside: renderComponents(component?.aside || []),
          footer: renderComponents(component?.footer || []),
          ...component?.buttonGroup&&{buttonGroup: component.buttonGroup},
        },
        renderComponents( (component.body || []).concat(component.definitions || []) )
      );
    });
  }

  return renderComponents.bind(null, schemas, extra)
}